<template>
  <div class="dataEdit">
    <el-row>
      <el-col :span="Template.allowBestFitColumns===2&&formData.StatusCode>0?19:24">
        <vxe-button status="success" v-if="showedit" content="修改" size="mini" @click="doedit"></vxe-button>
          <vxe-button status="success" v-if="statusCode===0&&canEdit" :content="formSet.save?formSet.save:'保存'" size="mini" @click="Save()"></vxe-button>
          <vxe-button status="success" v-if="formData.StatusCode===0&&Template.allowBestFitColumns===2" content="提交" size="mini" @click="addTask()"></vxe-button>
          <vxe-button v-if="statusCode===0&&canEdit" size="mini" status="primary" transfer placement="bottom" v-for="(items,key) in ManualActRules" :key="key">
            <template #default>{{ key }}</template>
            <template #dropdowns>
              <vxe-button type="text" v-for="(item,index) in items" :content="item.ruleName" :key="index" v-show="item.isExtFlow===0||(item.isExtFlow===1&&![1,2,8].includes(formData.StatusCode))"   @click="runActRules(item)"></vxe-button>
            </template>
          </vxe-button>
        <vxe-button size="mini"  v-if="printTemplates.length>0">
          <template #default>打印</template>
          <template #dropdowns>
              <vxe-button v-if="printTemplates.length>0" v-for="item in printTemplates" @click="handlePrint(item)" >{{ item.name }}</vxe-button>
          </template>
        </vxe-button >
          <div style="float: right; font-size: 1.3em;    margin-right: 50px;"> {{ Template.Title }}</div>
        <vxe-form :data="formData" :ref="el=>{refForm=el}" :rules="Rules[MT.tableName]" size="small" title-width="100" >
          <vxe-form-item :visible="false" field="RecordID"></vxe-form-item>

          <vxe-form-item v-for="(item,index) in  FormStyles['mainList']" :key="item.fieldID" :span="item.span"
                         :title="item.title" :visible="item.show" :field="item.fieldName"
                         :title-width="100" title-overflow
                         :item-render="{events:{change:ValueChange}}">
            <template #default="{ data }">
              <vxe-input v-if="item.componentType==='text'" v-model="data[item.fieldName]"  :readonly="item.permission" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>

              <el-input v-else-if="item.componentType==='list'" size="default"  @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"
                        placeholder="请点击选择..."  :readonly="item.permission" type="text" :value="getextend(data,item)">
                <template #append>
                  <el-button :disabled="item.editable===0" @click="showSource({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName})"
                             size="default" :icon="Plus"/>
                </template>
              </el-input>
              <el-input v-else-if="item.componentType==='map'||item.componentType==='warpWeft'" size="default"  @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"
                        placeholder="请点击选择..."  :readonly="item.permission" type="text" v-model="data[item.fieldName]">
                <template #append>
                  <el-button :disabled="item.editable===0" @click="clickMap(item.componentType,data,item.fieldName)"
                             size="default" :icon="Plus"/>
                </template>
              </el-input>

<!--              <vxe-select  v-else-if="item.componentType==='down'" :disabled="item.editable===0||statusCode!==0"-->
<!--                          v-model="data[item.fieldName]" placeholder="下拉框" clearable-->
<!--                          @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)" transfer>-->
<!--                <vxe-option v-for="(it,index) in Combo[item.fieldName]" :value="it.value" :label="it.label"-->
<!--                            :key="index"></vxe-option>-->
<!--              </vxe-select>-->

              <sx-select v-else-if="item.componentType=='down'&&item.permission" :type="item.Downoption" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"
                         :opitons="Combo[item.fieldName]" v-model="data[item.fieldName]"></sx-select>
              <sx-select v-else-if="item.componentType=='down'&&!item.permission" :type="item.Downoption" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"
                         :opitons="Combo[item.fieldName]" v-model="data[item.fieldName]" :disabled="false"></sx-select>

              
              <vxe-input v-else-if="item.componentType==='automaticText'"  v-model="data[item.fieldName]"
                         :readonly="item.permission" placeholder="自动取得编号"
                         @suffix-click="getAutoCode( Fields[MT.tableName],formData,item.fieldName,MT.tableName)">
                <template #suffix><i class="el-icon-refresh-right"></i></template>
              </vxe-input>
              <vxe-textarea v-else-if="item.componentType==='textarea'" v-model="data[item.fieldName]" :readonly="item.permission" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)" :autosize="{minRows: 3, maxRows: 3}" clearable></vxe-textarea>
              <vxe-input v-else-if="item.componentType==='integer'" v-model="data[item.fieldName]" :readonly="item.permission" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)" type="integer"></vxe-input>
              <vxe-input v-else-if="item.componentType==='floating'" v-model="data[item.fieldName]" :readonly="item.permission" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)" type="float"></vxe-input>
<!--              <div v-if="item.type===1">-->

<!--                <vxe-input v-model="data[item.fieldName]" v-show="item.componentID===0" :readonly="item.editable===0||statusCode!==0"-->
<!--                           @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>-->
<!--                <el-input size="default" v-show="item.componentID>0"-->
<!--                          @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"-->
<!--                          placeholder="请点击选择...123"  :readonly="item.editable===0||statusCode!==0"-->
<!--                          v-if="item.componentID>0 && [3,6].includes(item.componentType)" type="text"-->
<!--                          :value="getextend(data,item)">-->
<!--                  <template #append>-->
<!--                    <el-button :disabled="item.editable===0" @click="showSource({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName})"-->
<!--                               size="default" :icon="Plus"/>-->
<!--                  </template>-->
<!--                </el-input>-->
<!--                <vxe-select v-if="item.componentID>0 && item.componentType===1" :disabled="item.editable===0||statusCode!==0"-->
<!--                            v-model="data[item.fieldName]" placeholder="下拉框" clearable-->
<!--                            @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)" transfer>-->
<!--                  <vxe-option v-for="(it,index) in Combo[item.fieldName]" :value="it.value" :label="it.label"-->
<!--                              :key="index"></vxe-option>-->
<!--                </vxe-select>-->
<!--                <vxe-input v-if="item.componentID>0 && item.componentType===5" v-model="data[item.fieldName]"-->
<!--                           :readonly="item.editable===0||statusCode!==0" placeholder="自动取得编号"-->
<!--                           @suffix-click="getAutoCode( Fields[MT.tableName],formData,item.fieldName,MT.tableName)">-->
<!--                  <template #suffix><i class="el-icon-refresh-right"></i></template>-->
<!--                </vxe-input>-->
<!--              </div>-->
<!--              <vxe-input v-if="item.type===2" v-model="data[item.fieldName]" :readonly="item.editable===0||statusCode!==0"-->
<!--                         placeholder="请输入..." type="integer"-->
<!--                         @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>-->
<!--              <vxe-input v-if="item.type===3" v-model="data[item.fieldName]" :readonly="item.editable===0||statusCode!==0"-->
<!--                         placeholder="请输入..." clearable type="float" :digits="item.fieldPrecision"-->
<!--                         @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>-->
              <vxe-input  v-else-if="item.componentType==='date'" v-model="data[item.fieldName]" :readonly="item.editable===0||statusCode!==0" transfer
                         placeholder="请输入..." clearable type="date"
                         @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>
              <div v-if="[5,10].includes(item.type)">
                <vxe-input v-model="data[item.fieldName]" v-show="false"></vxe-input>
                <!-- <vxe-input  :value="getextend(data,item)" placeholder="请选择图片" readonly   class="my-search" @suffix-click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:false,fileType:'images'})" @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)">
                  <template #suffix >
                    <el-icon><Plus /></el-icon>
                  </template>
                </vxe-input> -->
                <el-input size="default" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"
                          placeholder="请选择图片" :readonly="item.editable===0||statusCode!==0"
                          type="text" :value="getextend(data,item)">
                  <template #append>
                    <el-button
                        @click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:false,fileType:'images'})"
                        size="default" :icon="Plus"/>
                  </template>
                </el-input>
              </div>
              <div v-else-if="item.componentType==='accessory'">
                <vxe-input v-model="data[item.fieldName]" v-show="false"></vxe-input>
                <el-input size="default" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"
                          placeholder="请选择文件" :readonly="item.editable===0||statusCode!==0" @dblclick="showFilesImage"
                          type="text" :value="getextend(data,item)">
                  <template #append>
                    <el-button
                        @click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:true,fileType:'files'})"
                        size="default" :icon="Plus"/>
                  </template>
                </el-input>
              </div>
<!--              <vxe-input v-if="item.type===7" v-model="data[item.fieldName]"-->
<!--                         placeholder="请输入..." clearable :readonly="item.editable===0||statusCode!==0"-->
<!--                         @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>-->
<!--              <vxe-input v-if="item.type===8" v-model="data[item.fieldName]" placeholder="请输入..."-->
<!--                         :readonly="item.editable===0" clearable @keyup="parseCode({event:$event,field:item,data:data})"-->
<!--                         @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>-->
            </template>
          </vxe-form-item>
          <!-- <vxe-form-item field="Extend" :visible="false"></vxe-form-item> -->
        </vxe-form>
       <el-tabs v-if=" FormStyle['tableList']">
            <el-tab-pane :label="item.tableTitle" v-for="(item ,name) in FormStyle['tableList']" >
              <vxe-toolbar v-show="FormStyle['tableList']" size="mini" :buttons="toolbarButtons"
                           @button-click="(value)=>buttonsClick(value,item.tableName,name)">
              </vxe-toolbar>
              <vxe-table border keep-source show-overflow :id="item.tableName" size="small" auto-resize :height="item.excelFormulaAutoFill===0?500:item.excelFormulaAutoFill"
                         :edit-rules="Rules[item.tableName]" :column-config="{resizable: true}" :mouse-config='{selected: true}'
                         :keyboard-config='{isArrow: true, isDel: true, isEnter: true, isTab: true, isEdit: true, isChecked: true}'
                         :checkbox-config="{highlight: true}" :data="DetailsData[item.tableName]"
                         :ref="el=>itemRefs[item.tableName]=el"
                         :edit-config="{trigger: 'click', mode: 'cell',showIcon:false, showStatus: true,enabled:statusCode===0} "
                         :show-footer="ShowFooter[item.tableName]"
                         :footer-method="footerMethod"
                         :tree-config="item.layoutStyle.length>0?{ transform: true,rowField: item.layoutStyle[0],parentField: item.layoutStyle[1]}:null"
                         :expand-config="expandConfig"
                         :loading="tableLoad[item.tableName]"
                         :sort-config="{defaultSort:item.Orders}"
                         :span-method="mergeRowMethod"
                         :row-config="{isCurrent: true, isHover: true}" @cellDblclick="showFilesImage">
                <vxe-column type="seq" align="center" width="60"></vxe-column>
                <vxe-column title="行号" field="Seq" align="center" :visible="false" width="60"></vxe-column>
                <vxe-column type="expand" align="center"  width="100"
                            v-if="Linker[item.tableName]!==undefined&&Linker[item.tableName].length>0">
                  <template #default="{ row }">
                    <vxe-button v-for="ite in Linker[item.tableName] " status="primary" size="mini" :content="ite.title"
                                @click="showExpand(item.tableName,row,ite.linkerID)"></vxe-button>
                  </template>
                  <template #content="{ row }">
                    <div class="expand-wrapper">
                      <vxe-grid :columns="expandField" :data="expandData[row.Seq]" auto-resize max-height="500"
                                :column-config="{resizable:true}">
                        <template #operate="{ row ,column }">
                          <vxe-button status="primary" size="mini" :content="column.params['button_title']"
                                      @click="doExpand(row,Linker[item.tableName],item.tableName)"></vxe-button>
                        </template>
                      </vxe-grid>
                    </div>
                  </template>
                </vxe-column>
                <vxe-column type="checkbox" align="center" width="40"></vxe-column>
                <vxe-column v-for="it in item.column" :field="it.fieldName"  :key="it.fieldID"
                            :width="it.allowFixedWidth>0?it.allowFixedWidth:(item.layoutStyle[0]===it.fieldName?200:100)"
                            :title="it.fieldDispName"
                            :formatter="formatData"
                            :header-align="'center'"
                            :visible="it.hidden===0"
                            sortable
                            :params="{column:it}"
                            :show-overflow="it.showRichText!==1"
                            :tree-node="item.layoutStyle.length===0?false:item.layoutStyle[0]===it.fieldName"
                            :edit-render="{autofocus: '.vxe-input--inner',enabled:it.editable===1}"             >

                  <template #header="{ column }">{{ column.title }}
                    <vxe-button v-if="item.layoutStyle[0]===column.field" status="primary"
                                style="height: 20px;width:40px;padding:0;" content="收展"
                                @click="extendTree(item.tableName)"></vxe-button>
                  </template>
                  <template #edit="{ row }" >
                    <vxe-input v-if="it.componentType==='text'" v-model="row[it.fieldName]" @change="ValueChange(row,Fields[it.tableName],it.fieldName,item.tableName)" :readonly="it.editable===0||statusCode!==0"></vxe-input>
                    <vxe-textarea v-else-if="it.componentType==='textarea'" v-model="row[item.fieldName]" @change="ValueChange(row,Fields[it.tableName],it.fieldName,item.tableName)" :autosize="{minRows: 3, maxRows: 3}" clearable></vxe-textarea>
                    <vxe-input v-else-if="it.componentType==='integer'" v-model="row[item.fieldName]" @change="ValueChange(row,Fields[it.tableName],it.fieldName,item.tableName)" type="integer"></vxe-input>
                    <vxe-input v-else-if="it.componentType==='floating'" v-model="row[item.fieldName]" @change="ValueChange(row,Fields[it.tableName],it.fieldName,item.tableName)" type="float"></vxe-input>
                    <vxe-input v-else-if="it.componentType==='automaticText'"  v-model="data[item.fieldName]"
                              :readonly="it.editable===0||statusCode!==0" placeholder="自动取得编号"
                              @suffix-click="getAutoCode( Fields[it.tableName],row,it.fieldName,item.tableName)">
                      <template #suffix><i class="el-icon-refresh-right"></i></template>
                    </vxe-input>
                    <el-input v-else-if="it.componentType==='list'" size="default"  @change="ValueChange(row,Fields[it.tableName],it.fieldName,item.tableName)"
                              placeholder="请点击选择..."  :readonly="item.editable===0||statusCode!==0" type="text" :value="getextend(row,it)">
                      <template #append>
                        <el-button :disabled="it.editable===0" @click="showSource({item:it ,value:row[it.fieldName],target:row,ref:item.tableName})"
                                  size="default" :icon="Plus"/>
                      </template>
                    </el-input>
                    <vxe-select  v-else-if="it.componentType==='down'" :readonly="it.editable===0"
                                v-model="row[it.fieldName]" placeholder="下拉框" clearable
                                @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)" transfer>
                      <vxe-option v-for="(it,index) in Combo[it.fieldName]" :value="it.value" :label="it.label"
                                  :key="index"></vxe-option>
                    </vxe-select>

                    <sx-select v-else-if="it.componentType==='down'" :multiple="it.Downoption==='selection'" @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"
                               :opitons="Combo[it.fieldName]" v-model="row[it.fieldName]" :disabled="it.editable===0||statusCode!==0"  ></sx-select>



                    <vxe-input  v-else-if="it.componentType==='date'" v-model="row[it.fieldName]" placeholder="请输入..."
                               :readonly="it.editable===0" transfer clearable type="date"
                               @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                    <div  v-else-if="it.componentType==='accessory'" >
                      <vxe-input v-model="row[it.fieldName]" v-show="false"></vxe-input>
                      <el-input size="default" @change="ValueChange(row,Fields[it.tableName],it.fieldName,it.tableName)"
                                placeholder="请选择文件" :readonly="it.editable===0||statusCode!==0"
                                type="text" :value="getextend(row,it)">
                        <template #append>
                          <el-button :disabled="it.editable===0"
                                     @click="showFiles({item:it ,value:row[it.fieldName],target:row,ref:item.tableName,multiple:true,fileType:'files'})"
                                     size="default" :icon="Plus"/>
                        </template>
                      </el-input>
                    </div>
                    <!-- <div v-if="it.componentType==='text'">
                      <vxe-input v-model="row[it.fieldName]" v-show="it.componentID===0" :readonly="it.editable===0"
                                 @blur="ValueChange(row,Fields[it.tableName],it.fieldName,item.tableName)"></vxe-input>
                      <el-input v-if="it.componentID>0 && [3,6].includes(it.componentType)" :value="getextend(row,it)"
                                 v-show="it.componentID>0" placeholder="请点击选择..." readonly
                                @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)">
                        <template #append>
                          <el-button :disabled="it.editable===0" @click="showSource({item:it ,value:row[it.fieldName],target:row,ref:item.tableName})"
                                     size="default" :icon="Plus"/>
                        </template>
                      </el-input>
                      <vxe-select v-if="it.componentID>0 && it.componentType===1" :readonly="it.editable===0"
                                  v-model="row[it.fieldName]" placeholder="下拉框" clearable
                                  @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)" transfer>
                        <vxe-option v-for="(it,index) in Combo[it.fieldName]" :value="it.value" :label="it.label"
                                    :key="index"></vxe-option>
                      </vxe-select>
                      <vxe-input v-if="it.componentID>0 && it.componentType===5" v-model="row[it.fieldName]"
                                 :readonly="it.editable===0" placeholder="自动取得编号"
                                 @suffix-click="getAutoCode( Fields[item.tableName],row,it.fieldName,item.tableName)">
                        <template #suffix><i class="el-icon-refresh-right"></i></template>
                      </vxe-input>
                    </div>
                    <vxe-input v-if="it.dataTypeID===2" v-model="row[it.fieldName]" placeholder="请输入..."
                               :readonly="it.editable===0" type="integer"
                               @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                    <vxe-input v-if="it.dataTypeID===3" v-model="row[it.fieldName]" placeholder="请输入..." autoselect
                               :readonly="it.editable===0" type="float" :digits="it.fieldPrecision"
                               @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>

                    <div v-if="[5,10].includes(it.dataTypeID)">
                      <vxe-input v-model="row[it.fieldName]" v-show="false"></vxe-input>
                      <vxe-input :value="getextend(row,it)" placeholder="请选择图片" readonly class="my-search"
                                 @suffix-click="showFiles({item:it ,value:row[it.fieldName],target:row,ref:item.tableName,multiple:false,fileType:'images'})"
                                 @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)">
                        <template #suffix>
                          <el-icon>
                            <Plus/>
                          </el-icon>
                        </template>
                      </vxe-input>
                    </div>

                    <vxe-input v-if="it.dataTypeID===7" v-model="row[it.fieldName]" placeholder="请输入..."
                               :readonly="it.editable===0" clearable
                               @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                    <vxe-input v-if="it.dataTypeID===8" v-model="row[it.fieldName]" placeholder="请输入..."
                               :readonly="it.editable===0" clearable
                               @change="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column title="操作" :fixed="!isequipment?'':'right'" width="230" v-if="item.layoutStyle.length>0&&statusCode===0">
                  <template #default="{ row }">
                    <vxe-button type="text" status="primary" icon="fa fa-cube" @click="insertTreeRow(item,row, 'current')">
                      平级
                    </vxe-button>
                    <vxe-button type="text" status="primary" icon="fa fa-cubes" @click="insertTreeRow(item,row, 'bottom')">
                      下级
                    </vxe-button>
                    <vxe-button type="text" status="primary" icon="fa fa-trash-o" @click="deleteTreeRow(item,row)"
                                v-if="candelete(item,row)">删除
                    </vxe-button> -->
                  </template>
                </vxe-column>
              </vxe-table>
            </el-tab-pane>
          </el-tabs>
      </el-col>
      <el-col :span="Template.allowBestFitColumns===2&&formData.StatusCode>0?5:0" style="border: 1px dashed green;padding: 10px;">

        <div style="height: 550px;">
          <sxPse :data="ApprovalData.task"></sxPse>
        </div>
        <div>
          <vxe-form  v-if="ApprovalData.do"
              title-colon
              ref="xForm"
              title-width="100"
              :data="ApprovalData"
              :rules="ApprovalRules"
              @submit="flowtodo">

            <vxe-form-item field="status" span="24" :item-render="{}" v-if="ApprovalData.task[ApprovalData.level].nodeName!=='退回发起人'">
                <template #default="{ data }">
                  <vxe-radio-group v-model="data.status" @click="approstatus">
                    <vxe-radio :label="8" content="同意"></vxe-radio>
                    <vxe-radio :label="7" content="退回"></vxe-radio>
                    <vxe-radio :label="9" content="拒绝"></vxe-radio>
                  </vxe-radio-group>
                </template>
              </vxe-form-item>
            <vxe-form-item field="opinion" span="24" :item-render="{}" v-if="ApprovalData.task[ApprovalData.level].nodeName!=='退回发起人'">
            <template #default="{ data }">
              <vxe-textarea v-model="data.opinion" placeholder="请输入审批意见" :autosize="{minRows: 3, maxRows: 3}" clearable></vxe-textarea>
            </template>
          </vxe-form-item>
            <vxe-form-item align="center" span="24">
              <template #default="{ data }">
                <vxe-button status="primary" v-if="data.status===8" @click="addproc()" content="加签"></vxe-button>
                <vxe-button type="submit" status="primary" content="提交"></vxe-button>
                <vxe-button type="reset" content="重置"></vxe-button>
              </template>
            </vxe-form-item>
          </vxe-form>
        </div>
      </el-col>
    </el-row>
    <DataGridSelect ref="DGE" :isequipment="isequipment" @submit="getSourceData"></DataGridSelect>
    <FilesSelect ref="Files" :isequipment="isequipment" @submit="getFilesData"></FilesSelect>
    <print ref="Print"></print>
    <organization ref="Organization" @selectUser="addsign"></organization>
    <el-dialog
      v-model="dialogMap"
      width="60%"
    ><locationmmap :mapType="mapType" @pushValue="weftWarp"></locationmmap></el-dialog>
  </div>
</template>

<script>
import {getCurrentInstance, onMounted, reactive, ref, toRefs, watch} from "vue"
import XEUtils from 'xe-utils'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
    getDefault,
    getdingfileid,
    getfilter,
    getForm,
    getSelectRule,
    loadExpand,
    rePost, reSendmsg,
    RunExpand,
    updateRule,
    uploaddingfileid
} from "/@/api/linkoo/form/index"
import {useRoute, useRouter} from 'vue-router'
import {Plus} from '@element-plus/icons-vue'
import {editForm} from "/@/api/linkoo/form"
import DataGridSelect from './select.vue'
import organization from './organization.vue'
import FilesSelect from './FilesSelect.vue'
import {mathAll} from "/@/utils/mathji"
import {useStore} from '/@/store';
import {getCode, getDingTalksCheck} from '/@/api/login'
import {flowTodo,getWorkFlowData} from "/@/api/linkoo/workflow";
import sxPse from "./sxpse.vue"
import Postlog from "../components/postlogs.vue"
import print from "/@/views/linkoo/print/print.vue"
import {getPrintList} from "/@/api/linkoo/print";
import  sxSelect from  "/@/views/linkoo/components/sxSelect.vue"
import locationmmap from "./locationmap.vue"
export default {
  props: ['Fieldss',"formSet", 'MT','typetem', 'DT', 'Combo', 'isequipment', 'Rules', 'ActRules', 'Action','isNew', 'Template', 'DataSource', 'load', 'Linker','FormStyle'],
  components: {DataGridSelect, FilesSelect,sxPse,print,organization,sxSelect,locationmmap},
  setup(props, ctx) {
    const {proxy} = getCurrentInstance()
    let Print = ref()
    let Organization = ref()
    let DGE = ref(null)
    let Files = ref(null)
    let refForm = ref(null)
    let router = useRouter()
    let store = useStore()
    let formData = ref({})
    const route = useRoute()
    let state = reactive({
      opinion:{8:'同意',7:'退回',9:'拒绝'},
      statusCode:0,
      RecordID: 0,
      mapType:"",//地图类型
      mapFilde:"",//地图当前选中字段
      validateCheck: true,
      OldMData: {},
      OldDData: {},
      selectMainData: {},
      printTemplates: [],
      dialogMap:false,
      DetailsData: {},
      selectTab: null,
      tableHeight: {},
      filterType:{options:[]},
      FormStyles:{mainList:[]},
      resize: '',
      template: {},
      AllData: {},
      firstload: true,
      linker: {},
      ManualActRules: {},
      tableLoad: {},
      rid: route.params.id,
      itemRefs: {},
      toolbarButtons: [
        {code: 'add', name: '新增'}, {code: 'copy', name: '复制'}, {code: 'clear', name: '清空'}, {
          code: 'delete',
          name: '删除'
        },  { name: '其它',  dropdowns: [
            { code: 'showSeq', name: '显示行号', type: 'text', },
            { code: 'test', name: '测试', type: 'text', },
          ]}
      ],
      mergeCellField:[],
      selectDataGridTarget: {},
      selectFiels: {},
      ApprovalData: {task:[]},
      ApprovalRules: {},
      ShowFooter: {},
      FooterFields: {},
      expandcfg: {},
      DataSource: {},
      expandField: [],
      Fields: [],
      expandData: {},
      expandrow: {},
      parentV: '',
      hjfield: [],
      filters:{},
      TreeExpand: false,
      wkedit: false,
      wkeditls: false,
      canEdit:false,
      showedit:false,
      DFV:{},
      workFlowWidth:3,
      expandConfig: {
        accordion:true,
        lazy: true,
        loadMethod({row}) {
          return new Promise(resolve => {
            loadExpand(state.expandcfg).then(res => {
              state.expandField = res.data.field
              state.expandData[row.Seq] = res.data.list
              resolve()
            })
          })
        },
        visibleMethod() {
          return false
        }
      },
    })
    watch(props, (ovl, evl) => {
      if (props.load && state.firstload) {
        state.firstload = false
        Load(1)
      }
    })
    onMounted(() => {
    })
    const weftWarp = (value)=>{
      console.log(state.mapType);
      if(state.mapType=="warpWeft"){
        //let str = value.lat+','+value.lon
        console.log(value);
        formData.value[state.mapFilde]=value.lonlat
        
        state.dialogMap=false
        state.mapFilde=''
      }else{
        formData.value[state.mapFilde]=value.address
        state.dialogMap=false
        state.mapFilde=''
      }
    }
    const mergeRowMethod = ({ row, _rowIndex, column, visibleData }) => {
      const fields = state.mergeCellField
      const cellValue = row[column.field]
      if (cellValue && fields.includes(column.field)) {
        const prevRow = visibleData[_rowIndex - 1]
        let nextRow = visibleData[_rowIndex + 1]
        if (prevRow && prevRow[column.field] === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow[column.field] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex]
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 }
          }
        }
      }
    }
    const Load = (type) => {
      let AllData = {}
      if (type === 1) {
        AllData = props.DataSource
      } else {
        AllData = state.AllData
      }
      
          // return
      XEUtils.arrayEach(props.DT, row => {
        state.ShowFooter[row.tableName] = false
        state.FooterFields[row.tableName]=[]
      })
      // if (props.DataSource[props.MT.tableName]) {
      state.OldMData = XEUtils.omit(AllData, 'ChildTables')
      formData.value = XEUtils.omit(AllData, 'ChildTables')
      state.Fields = XEUtils.clone(props.Fieldss, true)
      if(props.Template.templateType==4){
        console.log(props.typetem,route.params.templateCode);
        const tt= props.typetem.info[route.params.templateCode]
        const ft= props.typetem.info[tt.template.enterDirect]
        const ftb=XEUtils.find(ft.tables,item=>item.tableType===1)
        const tff= XEUtils.find(ft.tables,item=>item.tableType===0)
        const FV= props.typetem.filterData
        buildFilter(FV,tff.Fields,ftb)
      }
      state.RecordID = formData.value.RecordID
      state.canEdit = props.Action.canCreate>0&&![1, 2,8].includes(formData.value.StatusCode)
      // }
      if (AllData.ChildTables) {

        state.OldDData = XEUtils.clone(AllData.ChildTables, true)
        state.DetailsData = XEUtils.clone(AllData.ChildTables, true)
      }
      props.DT.forEach(row => {
        state.tableLoad[row.tableName]=false
        state.DFV[row.tableName]={RecordID: state.RecordID, Seq: null, Extend: '{}'}
        state.mergeCellField.push(...XEUtils.map(row.Fields.filter(item=>item.showCalendar===1),item=>item.fieldName))
        state.tableHeight[row.tableName] = document.documentElement.clientHeight-((state.Fields[row.tableName].filter(item=>item.hidden===0).length)*45)
        if (row.layoutStyle.length > 0 && row.onSheet.length > 0) {
          state.hjfield = state.hjfield.concat(row.onSheet)
        }
        const ff=row['onSheet'].toString()!==''?row['onSheet'].toString().split(','):[]
        if(ff.length>0){
          state.FooterFields[row.tableName]=state.FooterFields[row.tableName].concat(ff)
          state.ShowFooter[row.tableName]=true
        }
        XEUtils.objectEach(row.Fields,  (f, key) => {
                state.DFV[row.tableName][f['fieldName']] = null
          })

      })
      XEUtils.objectEach(props.ActRules, async (items, key) => {
        let rules = XEUtils.filter(items, item => item.runTime.split(',').includes('999'))
        if (rules.length > 0) {

          state.ManualActRules[key] = rules
        }
      })
      if (props.isNew && type === 1) {
        state.statusCode=0
        state.RecordID = 0
        state.showedit=true
        getDefaults(formData.value, props.MT.tableID)
      }
      if(props.Template.allowBestFitColumns===2&&formData.value.StatusCode>0){
        state.workFlowWidth=store.state.themeConfig.themeConfig.workFlowWidth?store.state.themeConfig.themeConfig.workFlowWidth:4
        GetWF()
      }
      doedit()
      getPrintList({tid:props.MT.templateID}).then(res=>{
        if(res.data.list&&res.data.list.length>0){
          state.printTemplates=res.data.list
        }

      })
      GetWF()
    }
    const buildFilter=(FV,tff,ftb)=>{
      const tp=tff[0].fieldName
      XEUtils.arrayEach(FV,item=>{
          state.filterType.options.push({label:item[tp],value:item[tp]})
          state.filterType['field']=item[tff[1].fieldName]
      })
      let tableDatasy = []
      props.typetem.filterData.forEach((item)=>{
        if(item['F1397']==formData.value[state.filterType.field]){
          item['ChildTables']['LK231'].forEach((v)=>{
            tableDatasy.push(v)
          })
        }
      })
      let arr = []
      tableDatasy.forEach((item)=>{
        props.FormStyle['mainList'].forEach((v)=>{
          if(item['F1399']==v.fieldName&&v.componentType!='array'){
            arr.push(v)
          }
        })
      })
      state.FormStyles['mainList']=[...arr]
      console.log(props.FormStyle['mainList'],formData.value[state.filterType.field]);
    }
    const clickMap = (type,data,field)=>{
      console.log("地图");
      state.mapType=type
      state.mapFilde=field
      state.dialogMap=true
    }
    const GetWF=()=>{
      console.log("123456");
      getWorkFlowData(props.Template.templateCode,formData.value.RecordID).then(res=>{
        if (res.data.task!==undefined&&res.data.task!==''){
          console.log(res.data);
          state.ApprovalData=res.data
          const extend=res.data.task[res.data.level]?res.data.task[res.data.level].extend:{}
          if(((extend.editor!==undefined&&extend.editor.length>0)||extend.fieldstatus===1)&&res.data.do){
            state.showedit=true
            state.wkeditls=true
            state.wkedit=false
            if(extend.fieldstatus===0&&extend.editor.length>0){
              const t=[],f =[]
              XEUtils.arrayEach(extend.editor,item=>{
                const k=item.split(".")
                t.push(k[0])
                f.push(k[1])
              })

              XEUtils.objectEach( state.Fields, (item, key) => {
                item.map(it=>{
                  it.editable=0;
                  if(t.includes(key)&&f.includes(it.fieldName)){
                    it.editable=1
                  }

                  return it})
              })
            }
          }
          if(res.data.do&&res.data.type===2){
            flowTodo(route.params.templateCode,route.params.id, state.ApprovalData.tid, {status:8,level:res.data.level}).then(res=>{
              GetWF()
            })
          }
        }

      })
    }

    const getDefaults = (target, id) => {
      getDefault(id).then(res => {
        console.log(res);
        XEUtils.objectEach(res.data, (item, key) => {
          target[key] = item
        })
        if (id === props.MT.tableID) {
          target['StatusCode'] = 0
        }
      })
      XEUtils.objectEach(props.ActRules, async (items) => {
        let selectrules = XEUtils.filter(items, item => item.runTime.split(',').includes('101') || item.runTime.split(',').includes('102'))
        for (let i = 0; i < selectrules.length; i++) {
          await loadSelectRules(selectrules[i])
        }
      })
    }
    const runActRules = (rule) => {
      ElMessage.success('执行程序中....'+rule.ruleName)
        console.log(rule)
      switch (rule.ruleType) {
        case 1:
          loadSelectRules(rule)
          break
        case 2:
          runUpdateRule(rule)
          break
        case 3:
          runPostRule(rule)
          break
        case 4:
              runSendMsg(rule)
              break

      }
    }
      const runSendMsg = async (rule) => {
          reSendmsg(formData.value.RecordID, rule.ruleID)
      }
    const runPostRule = async (rule) => {
      if (rule.isExtFlow === 1 && rule.sourceType === 1 ) {
        if((state.statusCode===99&&[1,2,8].includes(formData.value.StatusCode))||[1,2,8].includes(formData.value.StatusCode)){
          ElMessage.error('单据状态已变更,不允许再次提交!')
          return
        }
        let files = [], corpId = '', kk = getDingTalksCheck()
        await getdingfileid(rule.ruleID, formData.value.RecordID).then(async res => {
          files = res.data['fileId'] || [];
          corpId = res.data.corpId;
        })
        if (files.length > 0) {
          if (!kk) {
            ElMessage.error('有附件需要在钉钉客户端环境中上传,请在钉钉客户端中重试!')
            return
          } else {
            ElMessage.info('开始传送钉钉表单')
            let sendFiles = files.length
            for (let i = 0; i < files.length; i++) {
              await getCode(corpId, async (code) => {
                //  this.dingCode=code
                if (!code) {
                  ElMessage.error('未取得钉钉用户code')
                  // this.sendingLoading = false
                  return
                }
                await uploaddingfileid(files[i], code).then(res => {
                  ElMessage.success(res.message)
                  sendFiles--
                  if (sendFiles === 0) {
                    ElMessage.success("附件上传完毕!")
                    dopotrule(rule)
                  }
                })
              })
            }
          }
        } else {
          dopotrule(rule)
        }

      } else {
        dopotrule(rule)
      }

    }
    const dopotrule = (rule) => {
      rePost(formData.value.RecordID, rule.ruleID).then(res => {
        if (res.code === 0) {
          if (rule.isExtFlow === 1 && rule.sourceType === 1 ){
            state.statusCode=1
          }
          ElMessage.success('成功执行[' + rule.ruleName + ']')
        }
      })
    }
    const runUpdateRule = (rule) => {
      let filterExpr = rule.sqlSchema
      const regex = /({(\S+)[.](\S+)})/gis
      let m
      let keys = [], table = [], vals = []
      while ((m = regex.exec(filterExpr)) !== null) {
        // 这对于避免零宽度匹配的无限循环是必要的
        if (m.index === regex.lastIndex) {
          regex.lastIndex++
        }
        m.forEach((match, groupIndex) => {
          if (groupIndex === 1) {
            keys.push(match)
          }
          if (groupIndex === 2) {
            table.push(match)
          }
          if (groupIndex === 3) {
            vals.push(match)
          }
        })
      }
      XEUtils.arrayEach(keys, (it, key) => {
        if (table[key] !== props.MT.tableName && XEUtils.filter(props.DT, item => item.tableName === table[key])) {
          const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[key].getTableData().fullData, true), vals[key])
          filterExpr = filterExpr.replace(it, `'${data.join("','")}'`)
        } else {
          let val = XEUtils.get(formData.value, vals[key], "''")
          filterExpr = filterExpr.replace(it, val)
          filterExpr = filterExpr.replace('@RecordID', route.params.id.toString())
        }
      })
      updateRule(rule.ruleID, filterExpr, formData.value.RecordID).then(res => {
        if (res.code === 0) {
          ElMessage.success('成功执行[' + rule.ruleName + ']')
        }
      })
    }
    const loadSelectRules = async (rule) => {
      ElMessage.info('开始执行取数....')
      if (rule.ruleName === '合计') {
        const r = XEUtils.toStringJSON(rule.targetField)
        r.forEach(row => {
          const t = row.tofield.split('.')
          const f = row.field.split('.')
          if (t[0] === props.MT.tableName) {
            if (props.isequipment) {
              const $tb = state.itemRefs[f[0]]
              formData.value[t[1]] = XEUtils.sum($tb.getTableData().visibleData, f[1])
            } else {
              formData.value[t[1]] = XEUtils.sum(state.DetailsData[f[0]], f[1])
            }
          } else {
          }
        })
        return
      }
      let filterExpr = rule.filterExpr
      const regex = /({([a-zA-Z\d]+)[.]([a-zA-Z\d]+)})/gis
      let m
      let keys = [], table = [], vals = []
      while ((m = regex.exec(filterExpr)) !== null) {
        // 这对于避免零宽度匹配的无限循环是必要的
        if (m.index === regex.lastIndex) {
          regex.lastIndex++
        }
        m.forEach((match, groupIndex) => {
          if (groupIndex === 1) {
            keys.push(match)
          }
          if (groupIndex === 2) {
            table.push(match)
          }
          if (groupIndex === 3) {
            vals.push(match)
          }
        })
      }
      XEUtils.arrayEach(keys, (it, key) => {
        if (table[key] !== props.MT.tableName && filterExpr.indexOf(' in ') > 1) {
          const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[table[key]].getTableData().fullData, true), vals[key])
          filterExpr = filterExpr.replace(it, `'${data.join("','")}'`)
        } else {
          let val = XEUtils.get(formData.value, vals[key], '')
          if (val.length === 0&&state.itemRefs[table[key]]!==undefined) {
            const data = state.itemRefs[table[key]].getCurrentRecord()
            val = XEUtils.get(data, vals[key], "")
          }

          filterExpr = filterExpr.replace(it, val)
        }
      })
      await GetSelectRules(rule, filterExpr)
    }
    const GetSelectRules = async (rule, filterExpr) => {
      await getSelectRule(rule.ruleID, filterExpr).then(res => {
        if (res.data.list) {
          fromSelectRule(rule, res.data.list)
          ElMessage.success('成功执行[' + rule.ruleName + '],数据已添加')
        } else {
          ElMessage({type: 'info', message: '成功执行[' + rule.ruleName + '],但未到取到数据',})
        }
      })
    }
    const fromSelectRule =  (rule, data) => {
      if (data === null) return

      const topull = JSON.parse(rule['targetField'])
      let TB = {}, link = false, linkstr = ''
      topull.forEach(row => {
        const tf = row['tofield'].split('.')
        if (TB[tf[0]] === undefined) TB[tf[0]] = {}
        TB[tf[0]][tf[1]] = row['field'].indexOf('.') > -1 ? row['field'].split('.')[1] : row['field']
        if (row.type === 'keys') {
          link = true
          linkstr = tf[1]
        }
      })
      XEUtils.objectEach(TB, async (fields, key) => {
        if (key === props.MT.tableName) {
          XEUtils.objectEach(fields, (f, t) => {
            formData.value[t] = data[0][f]
          })
        } else {
          state.tableLoad[key]=true
          const $tb = state.itemRefs[key]
          let records = []
          for (let i=0;i<data.length;i++){

            const record = await getDTdefault(key)

            XEUtils.objectEach(fields, (f, t) => {
              record[t] = data[i][f]
            })
            records.push(record)
          }
          if (rule.clearAllRow === 1) {
            $tb.remove()
          }
          if (link) {
            const $tb = state.itemRefs[key]
            let dd =  $tb.getTableData().visibleData
            XEUtils.mapTree(dd, item => {
              const record = XEUtils.find(records, r => r[linkstr] === item[linkstr])
              if (record) {
                XEUtils.objectEach(record, (it, key) => {
                  if(it){
                    item[key] = it
                  }

                })
              }
              XEUtils.objectEach(state.Fields[key], async (field) => {
                if (field.componentType === 9 && field.componentFieldName !== '') {
                  const jgm = mathAll(field.componentFieldName, item)
                  item[field.fieldName] = jgm ? XEUtils.toFixed(jgm, field.fieldPrecision) : jgm
                }
              })
              return item
            })
            $tb.updateData(dd)
            setTimeout(()=>{
               getDFSum(key)
            },200)

          } else {
            if($tb.treeConfig){
              records=XEUtils.toArrayTree(records,{parentKey:$tb.treeConfig.parentField,key:$tb.treeConfig.rowField})
              records=XEUtils.toTreeArray(records,{clear:true})
              for(let i=0;i<records.length;i++){
                await $tb.insertAt(records[i])
              }
            }else{
              $tb.insertAt(records,-1)
            }

          }
          state.resize = key
          state.tableLoad[key]=false
        }
      })
    }
    //自上而下进行数量累计计算
    const updateTreeDataAdd = (treeData, fieldNameArray,maths) => {
      for (let i = 0; i < treeData.length; i++) {
        //只有存在子集时，才进行累加计算，否则不修改自身属性值
        if (treeData[i].children && treeData[i].children.length > 0) {
          //递归遍历并修改children的对应值
          treeData[i].children = updateTreeDataAdd(treeData[i].children, fieldNameArray,maths);
          // for (let k = 0; k < fieldNameArray.length; k++) {
          //   let fieldName = fieldNameArray[k];
            let addSum = 0.00;
            //循环相加计算和
            for (let j = 0; j < treeData[i].children.length; j++) {
              let childNum = treeData[i].children[j][fieldNameArray[1]];
              addSum += XEUtils.toNumber(childNum);
              //赋值
              treeData[i][fieldNameArray[0]] = XEUtils.toFixed(addSum, 2);
            }
          // }
          for (let field in maths)
          {
            treeData[i][field]=mathAll(maths[field], treeData[i])
          }
        }
      }
      return treeData;
    }

    const getDFSum = async (table) => {
      const $tb = state.itemRefs[table]
      await $tb.setAllTreeExpand(true)
      const tb = XEUtils.find(props.DT, item => item.tableName === table)
      $tb.updateData( updateTreeDataAdd($tb.getTableData().visibleData,tb.onSheet,tb.TreeSum))
    }
    const getextend = (data, field) => {
      //  console.log(data,field);
      let extend = XEUtils.toStringJSON(data['Extend'] ? data['Extend'] : '{}')
      if (extend[field.fieldName] === undefined) {
        extend[field.fieldName] = data[field.fieldName]
        //  console.log(data,extend,field.fieldName,"1234567890987654321");
        data['Extend'] = XEUtils.toJSONString(extend)
      }
      // console.log(XEUtils.get(extend,field.fieldName),"pppppp");
      return extend[field.fieldName]
    }
    const ValueChange = async (data, fields, fieldName, tableName) => {

      let source = XEUtils.clone(data, true)
      let extend = XEUtils.toStringJSON(data['Extend'])
      source = XEUtils.objectMap(source, item => item === null ? 0 : item)
      XEUtils.objectEach(fields, async (field) => {
        if (field.componentType === 9 && field.componentFieldName !== ''&& field.fieldName!==fieldName) {
          const jgm = mathAll(field.componentFieldName, source)
          data[field.fieldName] = jgm ? XEUtils.toFixed(jgm, field.fieldPrecision) : jgm
          if (state.hjfield.includes(field.fieldName)) {
            await getDFSum(tableName)
          }
        }

        if (field.dataTypeID !== 6 && field.componentType === 0 && extend[field.fieldName] !== null && extend[field.fieldName] !== undefined) {
          extend[field.fieldName] = data[field.fieldName]
        }
      })
      data['Extend'] = JSON.stringify(extend)

      setTimeout(async ()=>{XEUtils.objectEach(props.ActRules, async (items) => {
        let selectrules = XEUtils.filter(items, item => item.runTime.split(',').includes('106') && XEUtils.includes(item['onChangeFileld'].split(','), fieldName))
        for (let i = 0; i < selectrules.length; i++) {
          await loadSelectRules(selectrules[i])
        }
      })
        if (state.hjfield.includes(fieldName)) {
          await getDFSum(tableName)
        }
      },200)



    }
    const formatData = ({cellValue, row, column}) => {
      let extend = XEUtils.toStringJSON(row['Extend'])
      if (extend[column.field] === null || extend[column.field] === undefined) {
        extend[column.field] = cellValue ? cellValue : ''
      }
      return XEUtils.get(extend, column.field)
    }
    const deleteTreeRow = async (table, row) => {
      const $table = state.itemRefs[table.tableName]
      await $table.remove(row)
    }
    const candelete = (table, row) => {
      const $table = state.itemRefs[table.tableName]
      const data = $table.getData()
      return !data.filter(item => item[table.layoutStyle[1]] === row[table.layoutStyle[0]]).length > 0
    }
    const insertTreeRow = async (table, currRow, locat) => {
      const $table = state.itemRefs[table.tableName]
      let record = await getDTdefault(table.tableName)
      XEUtils.objectEach(state.Fields[table.tableName], (item, key) => {
        if (item.componentType === 9 && item.componentFieldName !== '') {
          const jgm = mathAll(item.componentFieldName, record)
          record[item.fieldName] = jgm ? XEUtils.toFixed(jgm, item.fieldPrecision) : jgm
        }
      })
      if (locat === 'current') {
        record[table.layoutStyle[1]] = currRow[table.layoutStyle[1]]
        state.parentV = currRow[table.layoutStyle[1]]
        const {row: newRow} = await $table.insertAt(record, -1)
        await $table.setEditRow(newRow) // 插入子节点
      } else if (locat === 'top') {
        record[table.layoutStyle[1]] = currRow[table.layoutStyle[0]]
        state.parentV = currRow[table.layoutStyle[0]]
        const {row: newRow} = await $table.insert(record)
        await $table.setTreeExpand(currRow, true) // 将父节点展开
        await $table.setEditRow(newRow) // 插入子节点
      } else if (locat === 'bottom') {
        record[table.layoutStyle[1]] = currRow[table.layoutStyle[0]]
        state.parentV = currRow[table.layoutStyle[0]]
        const {row: newRow} = await $table.insertAt(record, -1)
        await $table.setTreeExpand(currRow, true) // 将父节点展开
        await $table.setEditRow(newRow) // 插入子节点
      }
    }
    // const treeTotalSUM = async (fieldName, data) => {
    //   XEUtils.arrayEach(props.DT, async (table, index) => {
    //     if (table.layoutStyle.length > 0 && table.onSheet.includes(fieldName)) {
    //       const $tb = state.itemRefs[table.tableName]
    //       const datas = $tb.getTableData().tableData
    //       const pv = data[table.layoutStyle[1]]
    //       const P = XEUtils.findTree(datas, item => item[table.layoutStyle[0]] === pv)
    //       if (P !== undefined) {
    //         P.item[fieldName] = XEUtils.sum(P.item.children, fieldName)
    //         XEUtils.objectEach(state.Fields[table.tableName], (item, key) => {
    //           if (item.componentType === 9 && item.componentFieldName !== '' && !table.onSheet.includes(fieldName)) {
    //             const jgm = mathAll(item.componentFieldName, P.item)
    //             P.item[item.fieldName] = jgm ? XEUtils.toFixed(jgm, item.fieldPrecision) : jgm
    //           }
    //         })
    //         if (P.item[table.layoutStyle[1]] !== '') {
    //           await treeTotalSUM(fieldName, P.item)
    //         }
    //       }
    //     }
    //   })
    // }
    const getDTdefault = async (table,news) => {
      const row = state.DFV[table]
        const tb = XEUtils.find(props.DT, item => item.tableName === table)
        if(tb.allowWorkFlow>0){
        await getDefault(tb.tableID).then(res => {
          XEUtils.objectEach(res.data, (item, key) => {
            row[key] = item
          })
        })
      }

      return XEUtils.clone(row)
    }
    const buttonsClick = async ({code, button, $event}, name, index) => {
      if(state.statusCode!==0) {
      ElMessage.info("查看模式,操作无效")
        return
      }
      state.selectTab = name
      switch (code) {
        case 'add': {
          let target = await getDTdefault(name)
          XEUtils.objectEach(state.Fields[name], (item, key) => {
            if (item.componentType === 9 && item.componentFieldName !== '') {
              const jgm = mathAll(item.componentFieldName, target)
              target[item.fieldName] = jgm ? XEUtils.toFixed(jgm, item.fieldPrecision) : jgm
            }
          })
          const {row: fnewRow} = await state.itemRefs[name].insertAt(target, -1)
          await state.itemRefs[name].setActiveCell(fnewRow, state.Fields[state.selectTab][0]['fieldName'])
          await state.itemRefs[name].setCurrentRow(fnewRow)
          // this.tableHeight[this.selectTab]=this.tableHeight[this.selectTab]>500?this.tableHeight[this.selectTab]:this.tableHeight[this.selectTab]+40
          state.resize = fnewRow['_X_ID']
          break
        }
        case 'delete': {
          const Fieldrows = state.itemRefs[name].getCheckboxRecords()
          if (Fieldrows.length > 0) {
            ElMessageBox.confirm("您确定要删除该数据?", "警告", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              state.resize = Fieldrows[0]['_X_ID']
              state.itemRefs[name].remove(Fieldrows)
            })
          } else {
            ElMessage({type: 'info', message: '选择数据后再删除!',})
          }
          break
        }
        case 'clear': {
          ElMessageBox.confirm("您确定要清空数据吗?", "警告", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            state.itemRefs[name].remove()
          })
          break
        }
        case 'showSeq': {
          const field=state.itemRefs[name].getColumnByField("Seq")
          field.visible=!field.visible
          state.itemRefs[name].refreshColumn()
          break
        }
        case 'test': {
          // console.log('getData()',state.itemRefs[name].getData())
          // console.log('getTableData().fullData',state.itemRefs[name].getTableData().fullData)
          // console.log('getTableData().tableData',state.itemRefs[name].getTableData().tableData)
          // getDTDataSum(state.itemRefs[name].getTableData().tableData, XEUtils.find(props.DT, item => item.tableName === name))
          getDFSum(name)
          break
        }
        case 'copy': {
          const Fieldrows = state.itemRefs[name].getCheckboxRecords()
          if (Fieldrows.length > 0) {
            const fields = Fieldrows.map((row, index) => {
              row['RecordID'] = state.RecordID;
              row['Seq'] = null;
              row['Extend'] = '{}';

              delete row['_X_ROW_KEY'];
              return row
            })
            await state.itemRefs[name].insertAt(fields, -1)
            // this.tableHeight[this.selectTab]=40*Fieldrows.length+120>500?500:this.tableHeight[this.selectTab]+40*Fieldrows.length
          } else {
            ElMessage({
              type: 'info',
              message: '选择数据后再复制!',
            })
          }
          break
        }
      }
    }
    const extendTree = async (name) => {
      state.TreeExpand = !state.TreeExpand
      if (state.TreeExpand) {
        await state.itemRefs[name].setAllTreeExpand(state.TreeExpand)
      } else {
        await state.itemRefs[name].clearTreeExpand()
        state.itemRefs[name].updateFooter()
      }
    }
    const getAutoCode = (fields, target, field) => {
      if (field) {
        field = XEUtils.find(fields, item => item.fieldName === field)
        if (field.componentType === 5 && target[field.fieldName] !== '') {
          ElMessageBox.confirm("是否确认重新获取编号?", "警告", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            ElMessage({
              type: 'info',
              message: '确认重新获取编号',
            })
            // getAutoCodes(this.$route.name,field.componentID).then(res=>{
            //     target[field.fieldName]=res.data
            // })
          }).catch(function () {
          });
        }
      } else {
        XEUtils.objectEach(fields, (item, key) => {
          if (item.default !== '') {
            target[item.fieldName] = item.default
          }
          if (item.componentType === 5 && XEUtils.toValueString(target[item.fieldName]) === '') {
            // getAutoCodes(this.$route.name,item.ID).then(res=>{
            //     target[item.fieldName]=res.data
            // })
          }
        })
      }
    }
    const showSource = async ({item, value, target, ref}) => {
      console.log(item, value, target, ref);
      if(state.statusCode!==0)return
      if (item.componentFilterExpr !== '' && item.componentType === 'list') {
        if (state.filters[item.fieldName]===undefined){
          state.filters[item.fieldName]=XEUtils.clone(item.componentFilterExpr, true)
        }
        let filter = XEUtils.clone( state.filters[item.fieldName], true)
          const regex = /({(\S+)})/gis
          let m
          let keys = [], vals = []
          while ((m = regex.exec(filter)) !== null) {
            // 这对于避免零宽度匹配的无限循环是必要的
            if (m.index === regex.lastIndex) {
              regex.lastIndex++
            }
            // 结果可以通过`m变量`访问。
            m.forEach((match, groupIndex) => {
              if (groupIndex === 1) {
                keys.push(match)
              }
              if (groupIndex === 2) {
                vals.push(match)
              }
            })
          }
          XEUtils.arrayEach(keys, (it, key) => {
            //   // 主字段查找
            let val = XEUtils.get(formData.value, vals[key], '')
            if (val === '') {
              //     // 明细表行数据查找
              val = XEUtils.get(target, vals[key], '')
            }
            if (filter.indexOf(' in ') > 1) {
              const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[ref].getTableData().fullData, true), vals[key])
             // console.log(data,'dddddd')
              let vv=data?data.join("','"):''
              filter = filter.replace(it, `'${vv}'`)
            }else{
              filter = filter.replace(it, val)
            }
          })

        item.componentFilterExpr = filter
      }
      console.log('dddddd')
      DGE.value.Data = Object.assign({}, {field: item, value: value, data: formData.value})
      DGE.value.todo()
      DGE.value.keyword=''
      // this.$refs.DGE.showDialog = true
      state.selectDataGridTarget = {field: item, target: target, ref: ref}
    }
    const showFiles = async ({item, value, target, ref, multiple, fileType}) => {
      // if(state.statusCode!==0){
      //   return
      // }
      Files.value.Data = Object.assign({}, {field: item, value: value})
      Files.value.dataTypeID = item.dataTypeID
      Files.value.todo()
      Files.value.multiple = multiple
      Files.value.fileType = fileType
      Files.value.title = fileType === 'images' ? '图片选择' : '附件选择'
      Files.value.status =state.statusCode
      Files.value.fileSize = item.fieldPrecision === 0 ? 8 : item.fieldPrecision

      state.selectFiels = {field: item, target: target, ref: ref}
    }
    const getSourceData = ({data, data2, C}) => {
      // data是选中的数组
      const field = state.selectDataGridTarget.field.configList
      const target = state.selectDataGridTarget.target
      const keys = state.selectDataGridTarget.ref
      console.log(field,target,keys);
      let isBT = true
      if (XEUtils.has(target, 'Seq')) {
        isBT = false
      }
      const tb = XEUtils.find(props.DT, item => item.tableName === keys)
      if (isBT) {
        XEUtils.objectEach(field, (item, key) => {
          target[key] = XEUtils.pluck(data, item.v).join(",")
          let extend = XEUtils.toStringJSON(target['Extend'])
          const F = state.Fields[keys].find(item => item.fieldName === key)
          if (F!==undefined && F['componentType'] === 3) {
            extend[key] = XEUtils.pluck(data, item.v).join(",")
          }
          target['Extend'] = XEUtils.toJSONString(extend)
        })
      } else {
        data.forEach(async (row, index) => {

          const newrow = await getDTdefault(keys)
          if (tb.layoutStyle.length > 0) {
            newrow[tb.layoutStyle[1]] = state.parentV
          }
          XEUtils.objectEach(field, (item, key) => {
            // 对象迭代器，只能用于遍历对象，性能高于 each
            if (row[item.v]) {
              newrow[key] = row[item.v]
            }

            let extend = XEUtils.toStringJSON(newrow['Extend'])
            const F = state.Fields[keys].find(item => item.fieldName === key)
            if (F!==undefined &&F['componentType'] === 3) {
              extend[key] = data[index][item.v]
            }
            newrow['Extend'] = XEUtils.toJSONString(extend)
          })

          XEUtils.objectEach(state.Fields[keys], (item, key) => {
            if (item.componentType === 9 && item.componentFieldName !== '') {
              const jgm = mathAll(item.componentFieldName, newrow)
              newrow[item.fieldName] = jgm ? XEUtils.toFixed(jgm, item.fieldPrecision) : jgm
            }
          })
          if (tb.layoutStyle.length>0&&newrow[tb.layoutStyle[0]] === newrow[tb.layoutStyle[1]]) {
            return false
          }
          if (index === 0) {
            XEUtils.objectEach(newrow, (item, key) => {
              if (item) {
                target[key] = item
              }
            })
          } else {
            const $tb = state.itemRefs[keys]
            $tb.insertAt(newrow, -1)

          }
        })
      }
      ValueChange(target, state.Fields[keys], state.selectDataGridTarget.field.fieldName,keys)
    }
    // 移动端
    const addDataSou = (tableName) => {
      // console.log(tableName);
      state.selectTab = tableName
      const Max = XEUtils.max(state.DetailsData[state.selectTab], 'Seq')
      let seq = 0
      if (Max !== undefined) {
        seq = Max[['Seq']]
      }
      state.DetailsData[state.selectTab].push(getNewitem(state.selectTab, seq))
    }
    const getNewitem = (table, maxseq) => {
      const def = {}
      state.Fields[table].forEach(row => {
        def[row.fieldName] = null
      })
      def['Seq'] = maxseq + 1
      return def
    }
    const getFilesData = ({data, filesName, extdata}) => {
      state.selectFiels.target[state.selectFiels.field.fieldName] = data
      let extend = XEUtils.toStringJSON(state.selectFiels.target['Extend'])
      extend[state.selectFiels.field.fieldName] = filesName
      if (extdata.length > 0) {
        const field = JSON.parse(state.selectFiels.field.componentFieldName)
        for (let i = 0; i < extdata.length; i++) {
          if (i === 0) {
            XEUtils.objectEach(field, (item, key) => {
              state.selectFiels.target[key] = extdata[0][item]
            })
          } else {
            let rows = {}, ext = {}
            rows[state.selectFiels.field.fieldName] = data
            ext[state.selectFiels.field.fieldName] = filesName
            rows['Extend'] = XEUtils.toJSONString(ext)
            XEUtils.objectEach(field, (item, key) => {
              rows[key] = extdata[i][item]
            })
            // this.$refs[state.selectFiels.ref][0].insertAt(rows,-1)
          }
        }
      }

      state.selectFiels.target['Extend'] = XEUtils.toJSONString(extend)
    }
    const kk=(data)=>{
      console.log(data)
    }
    const Save = async () => {

      // if (formData.value.StatusCode !== 0) {
      //   ElMessage({
      //     message: '单据审核状态非初始状态.不能执行保存!',
      //     type: 'error',
      //   })
      //   return
      // }
      state.validateCheck = true
      const Data = {}
      Data['T'] = props.MT.templateID
      Data['D'] = await getDetailData()
      Data['M'] = await getMainData()
      console.log(Data);
      if (!state.validateCheck) {
        return;
      }
      console.log(Data);
      await editForm(route.params.templateCode, route.params.id, Data).then((response) => {
        let id=route.params.id
        if (response.code === 0) {
          ElMessage.success('单据操作成功')
          if (props.isNew) {

            proxy.mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));

           id=response.data.id
            // proxy.mittBus.on('onTagsViewRefreshRouterView', url)
            // store.commit("sxclick", '/form/edit/:templateCode/:id-' + route.params.templateCode + "0")
            // router.push({params: {id: response.data.id}, replace: true})
          }
          const url = '/form/edit/' + route.params.templateCode + "/" + id
          router.push(url)
          //router.go(0);
          //reloadData(response.data.id)

        } else {
          ElMessage.error('单据操作出错')
        }
      })

    }
    const reloadData = (id) => {
      getForm(route.params.templateCode, id, {}).then(response => {
        state.AllData = response.data
        Load(2)
      })
    }
    const getDetailData = async () => {
      const Data = {}
      for (const tb of props.DT) {
        const indext = props.DT.indexOf(tb);
        let data = []
        Data[tb.tableName] = {DE: [], DD: [], DA: []}
        const errMap = await state.itemRefs[tb.tableName].validate()
        if (errMap) {
          state.validateCheck = false
          continue;
        }
        const olddata = state.OldDData[tb.tableName] || []
        // let maidseq = olddata.length > 0 ? XEUtils.max(olddata, item => item.Seq)['Seq'] : 0
        // console.log(props.isequipment);
        // if (props.isequipment) {
        const tabledata = state.itemRefs[tb.tableName].getRecordset()
        const deleteRecords = tabledata.removeRecords
        data = XEUtils.orderBy(tabledata.insertRecords.concat(tabledata.updateRecords), '_X_ROW_KEY')

        data = data.map((row, index) => {
          delete row['_X_ROW_KEY']
          delete row['_X_ROW_CHILD']
          delete row['children']
          return row
        })
        Data[tb.tableName].DD = deleteRecords
        // } else {
        //   data = state.DetailsData[tb.tableName].concat([])
        // }
        data.forEach(rowData => {
          let od = XEUtils.find(olddata, item => item.Seq === rowData.Seq)
          if (od === undefined) {
            Data[tb.tableName].DA.push(rowData)
          } else {
            const updateData = {}
            XEUtils.objectEach(od, (item, key) => {
              if (item !== rowData[key] && key !== 'Seq' && key !== 'RecordID') {
                updateData[key] = rowData[key]
              }
            })
            if (!XEUtils.isEmpty(updateData)) {
              Data[tb.tableName].DE.push(XEUtils.assign(updateData, {
                'RecordID': rowData['RecordID'],
                'Seq': rowData['Seq']
              }))
            }
          }
        })
        // console.log(olddata);
        // olddata.forEach(row => {
        //   if (XEUtils.find(data, item => item.Seq === row.Seq) === undefined) {
        //     Data[tb.tableName].DD.push(row)
        //   }
        // })

      }
      return Data
    }
    const getMainData = async () => {
      const n = {}
      let data = {}
      const errMap = await refForm.value.validate()
      if (errMap) {
        state.validateCheck = false
        return
      }
      if (formData.value.RecordID === 0 || props.isNew) {
        data = formData.value
        data.RecordID = 0
        data.StatusCode = 0
      } else {
        XEUtils.objectEach(XEUtils.omit(formData.value, 'ChildTables'), (item, key) => {
          if ((key === 'Extend') || (state.OldMData[key] !== null && item !== state.OldMData[key]) || (state.OldMData[key] === null && item)) {
            data[key] = item
          }
        })
      }
      n[props.MT.tableName] = data
      const Data = XEUtils.clone(n, true)
      return Data
    }
    const sumNum = (list, field) => {
      let count = 0

      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    }
    const showExpand = (table, row, lid) => {
      state.expandcfg = {id: lid, row: row}
      state.expandrow = row
      const $tb = state.itemRefs[table]
      $tb.toggleRowExpand(row)
    }
    const doExpand = (row, link,name) => {
      const TR= XEUtils.toStringJSON(link[0].torow)
      XEUtils.objectEach(TR,(fromfield ,tofield)=>{
        state.expandrow[tofield]=row[fromfield]

      })
      RunExpand({row: row, id: link[0].linkerID}).then(res => {
        if (res.code === 0) {
          ElMessage.success('操作成功')
        } else {
          ElMessage.error('操作出错' + res.msg)
        }
      })

    }
    const footerMethod = ({$table, columns, data}) => {
      const tableName = $table.props.id
      // state.itemRefs[tableName].clearTreeExpand()
      // data=state.itemRefs[tableName].getTableData().visibleData

      if (state.ShowFooter[tableName]) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '合计'
            }
            if (state.FooterFields[tableName].includes(column.property)) {
              return sumNum(data, column.property)
            }
            return null
          })
        ]
      }

    }
    const flowtodo=()=>{
      const data=XEUtils.clone(state.ApprovalData)
          if(data.task[data.level].nodeName==='退回发起人'){
            data.status=8
            data.opinion="重新提交"
          }
          flowTodo(route.params.templateCode,route.params.id, state.ApprovalData.tid,data).then(res=>{
            proxy.mittBus.emit('onCurrentContextmenuClick', { contextMenuClickId: 0, ...route });
      })

    }
    const addsign=(users)=>{

      const data=XEUtils.clone(state.ApprovalData)
      if(users.length>0&&data.status===8){
        data['addsign']=users.map(user=>{
          return {id:user.id,name:user.userName,pid:"d"+user.deptId,types:"u"}
        })
        flowTodo(route.params.templateCode,route.params.id, state.ApprovalData.tid,data).then(res=>{
          proxy.mittBus.emit('onCurrentContextmenuClick', { contextMenuClickId: 0, ...route });
        })
      }
    }
    const doedit=()=>{
      if (state.canEdit){
        if (!state.showedit){
          state.statusCode=99
          state.showedit=true
        }else{
          state.statusCode=0
          state.showedit=false
        }
      }else{
        state.statusCode=formData.value.StatusCode
        state.showedit=false
      }
      if(state.wkeditls){
        state.statusCode=0
        state.canEdit=true
        // state.wkedit=true
      }
    }
    const getShowFooter = (tableName) => {
      return state.ShowFooter[tableName]
    }
    const showFilesImage = (data) => {
      if (state.statusCode===99&&[5,6,10].includes(data.column.params.column.dataTypeID)){
        const column=data.column.params.column
        const row=data.row
        const TableName=data.$table.props.id
       showFiles({item:column ,value:row[column.fieldName],target:row,ref:TableName,multiple:[6].includes(data.column.params.column.dataTypeID),fileType:[6].includes(data.column.params.column.dataTypeID)?'files':'images'})
      }
    }
    const addTask = () => {
      if(formData.value.RecordID===0){
        ElMessage.error('请先保存后再提交')
        return
      }
      flowTodo(route.params.templateCode,route.params.id, 0, {}).then(res=>{
        formData.value.StatusCode=1
        state.showedit=false
        GetWF()
      })
    }
    const parseCode=({event,field,data})=>{
      if(event.$event.keyCode===13){
        if(field.dataTypeID===8&& field.componentFieldName !== ''){
          const  codes=XEUtils.toStringJSON(field.componentFieldName)
          if(data[field.fieldName]&&data[field.fieldName].split(codes['separator']).length===codes['count']){
            data[field.fieldName]=data[field.fieldName].split(codes['separator'])[codes['size']]
          }
        }
      }
    }
    const approstatus = () => {
        setTimeout(()=>{
          state.ApprovalData.opinion=state.opinion[state.ApprovalData.status]
        },10)
    }
    const handlePrint  = async(item) => {
      let dm=formData.value
      dm['ChildTables']={}
       for (const tb of props.DT) {
           const tabledata = state.itemRefs[tb.tableName].getCheckboxRecords()
         if(tabledata.length>0){
           dm['ChildTables'][tb.tableName]=tabledata
         }else{
           dm['ChildTables'][tb.tableName]= state.itemRefs[tb.tableName].getData()
         }
       }
        const data={printData:item,rid:state.AllData.RecordID,DataSource:dm,Combo:props.Combo,maintable:props.MT,detailtable:props.DT}
       Print.value.Load(0,data)
    }
    const addproc = () => {
      Organization.value.showDialog()
    }
    return {
      ...toRefs(state)
      , Load,
      getDefaults,
      loadSelectRules,handlePrint,
      XEUtils,
      DGE,
      Files,
      Plus,Print,Organization,
      refForm,
      formData,
      insertTreeRow,addsign,
      getextend,
      GetWF,
      getShowFooter,
      showExpand,
      ValueChange,
      formatData,
      getMainData,
      weftWarp,
      getAutoCode,
      buttonsClick,
      showSource,
      clickMap,
      showFiles,
      getSourceData,
      addDataSou,
      getNewitem,
      doExpand,
      runPostRule,
      runActRules,
      getFilesData,
      Save,mergeRowMethod,addTask,approstatus,parseCode,
      candelete,
      deleteTreeRow,
      GetSelectRules,
      getDetailData,
      footerMethod,
      extendTree,
      flowtodo,
      doedit,addproc,
      showFilesImage
    }
  }
}
</script>

<style scoped>
.expand-wrapper {
  padding: 10px;
}
.index {
  position: absolute
}
td,th{
  vertical-align: middle;
}
.my-search.vxe-input .vxe-input--suffix {
  width: 33px;
  text-align: center;
  border: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  cursor: pointer;
  right: 0px;
}

.my-search.vxe-input .vxe-input--inner {
  border: 1px solid #dcdfe6;
}

.sxform .vxe-form--item .vxe-form--item-inner .vxe-form--item-content {
  width: 100%;
}
.stable {
  padding: 10px;
  box-sizing: border-box;
}

.ke {
  background-color: #ffffff;
  border: 1px dashed #3b3b3b;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
}

.ke .lie {
  display: flex;
  margin: 5px 0;
  align-items: center;
}

.ke .lie span {
  width: 90px;
}

.ke .lie input {
  flex: 1;
  height: 30px;
  border: 1px solid rgb(152, 152, 152);
  border-radius: 3px;
}

.addbut {
  width: 100%;
}

.addbut-red:focus, .addbut-red:active {
  border: 1px solid #ff8989;
  background-color: #ff898918;
  color: #ff8989;
}

.addbut-red {
  width: 100%;
  border: 1px solid #ff8989;
  background-color: #ff898918;
  color: #ff8989;
  margin-top: 10px;
}

.m-10 {
  margin-bottom: 10px;
}
</style>